package com.wswy.wzcx.ui.car.remind

import android.app.DatePickerDialog
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RadioGroup
import com.blankj.utilcode.util.SizeUtils
import com.che.libcommon.utils.ToastUtils
import com.wswy.wzcx.R
import com.wswy.wzcx.model.CarTypes
import com.wswy.wzcx.module.base.CBaseFragment
import com.wswy.wzcx.module.base.getColor
import com.wswy.wzcx.module.base.onClick
import com.wswy.wzcx.statistics.StatTools
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.dialog.ImgDialog
import com.wswy.wzcx.ui.dialog.LoadingDialog
import com.wswy.wzcx.ui.other.DialogFactory
import com.wswy.wzcx.utils.UiUtils
import com.wswy.wzcx.utils.append0
import kotlinx.android.synthetic.main.activity_add_car_info.*
import kotlinx.android.synthetic.main.fragment_add_inspection.*
import kotlinx.android.synthetic.main.fragment_add_inspection.btn_save
import kotlinx.android.synthetic.main.fragment_add_inspection.tv_car_no
import kotlinx.android.synthetic.main.fragment_add_new_inspection.*
import java.util.*
import kotlin.math.max

/**
 * 添加年检
 */
class InspectionAddFragment : CBaseFragment(){


    private lateinit var remindViewModel:RemindViewModel

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_add_inspection,container,false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)


        remindViewModel=provideViewModelFromActivity(RemindViewModel::class.java)
        remindViewModel.loadCompany()

        tv_car_no.text = remindViewModel.userCarInfo.carNo

        v_choose_reg_date.setUI("上牌时间","请选择")
        v_choose_validity_date.setUI("检验有效期至","请选择")

        v_choose_reg_date.setHelpClick {
            ImgDialog(v_choose_reg_date.context,R.drawable.pic_shangpaishijian).show()
        }

        v_choose_validity_date.setHelpClick {
            ImgDialog(v_choose_reg_date.context,R.drawable.pic_jianyanyouxiaoqi).show()
        }

        UiUtils.addOnGlobalLayoutListener(tv_hint_desc_title){

            ContextCompat.getDrawable(tv_hint_desc_title.context,R.drawable.add_car_line)?.let {drawable ->

                tv_hint_desc_title.layoutParams?.run {
                    width = ViewGroup.LayoutParams.MATCH_PARENT
                    tv_hint_desc_title.layoutParams = this
                }

                (tv_hint_desc_title.parent as? View)?.width?.minus(tv_hint_desc_title.width)?.div(2)?.let {

                    tv_hint_desc_title.compoundDrawablePadding = SizeUtils.dp2px(12f)

                    drawable.setBounds(0,0,it-tv_hint_desc_title.compoundDrawablePadding,SizeUtils.dp2px(1f))


                    tv_hint_desc_title.setCompoundDrawables(drawable,null,drawable,null)
                }

            }

        }

        remindViewModel.userCarInfo.carExtendInfo?.inspection?.run {

            v_choose_reg_date.setSelectedValue(regDate)
            v_choose_validity_date.setSelectedValue(validityDate)

            remindViewModel.addInspectionSaveChoose(regDate,validityDate)
        }


        v_choose_reg_date.onClick {

            val ymd = remindViewModel.addInspectionStatus.getYMD(remindViewModel.addInspectionStatus.regDate)
            ymd?.set(1,ymd[1]-1)

            showChooseDate(Calendar.getInstance().timeInMillis, ymd?:arrayOf(2018,0,1)) {
                v_choose_reg_date.setSelectedValue(it)

                remindViewModel.calInspectionData(it)

                remindViewModel.addInspectionSaveChoose(regDate = it)
            }
        }

        v_choose_validity_date.onClick {

            val ymd = remindViewModel.addInspectionStatus.getYMD(remindViewModel.addInspectionStatus.validityDate)
            ymd?.set(1,ymd[1]-1)

            showChooseDate(ymd = ymd?:arrayOf(2018,0,1)) {
                v_choose_validity_date.setSelectedValue(it)
                remindViewModel.addInspectionSaveChoose(validityDate = it)
            }
        }


        remindViewModel.getCalInspectionDate().observe(this,android.arch.lifecycle.Observer {

            it?.run {

                if (TextUtils.equals(v_choose_reg_date.getSelectedValue(),regDate)){

                    //更新时间

                    v_choose_validity_date.setSelectedValue(endDate)
                }

            }

        })

        btn_save.onClick {
            save()
        }

    }

    private fun save(){
        val date = v_choose_reg_date.getSelectedValue()
        val company = v_choose_validity_date.getSelectedValue()
        if (TextUtils.isEmpty(date)){
            ToastUtils.showText("请选择上牌时间")
            return
        }

        if (TextUtils.isEmpty(company)){
            ToastUtils.showText("请选择有效期")
            return
        }

        StatTools.sendClick(context, StatisticsId.addinspection_save)


        val dialog = LoadingDialog(context,"")

//        remindViewModel.addInspection(date?.toString(),company?.toString())

        remindViewModel.getAddInsuranceLiveData().observe(this,android.arch.lifecycle.Observer {

            it?.run {
                btn_save.isClickable = !inLoading()
                if(inLoading()){
                    dialog.show()
                }else{

                    if (isOk()){
                        dialog.setOnDismissListener {
                            (activity as? RemindActivity)?.run {
                                showInfo()
                            }
                        }
                        dialog.setSuccess("保存成功")
                        remindViewModel.setCarExtendInfo(data)

                    }else{

                        dialog.setSuccess("保存失败")
                    }
                }


            }

        })

    }


    private fun showChooseDate(maxDate:Long=0,ymd:Array<Int>, block:((String)->Unit)) {

        DialogFactory.createDatePickerDialog(context, DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->

            remindViewModel.addInsuranceSaveChoose(year, month, dayOfMonth)

            block.invoke("$year-${(month+1).append0()}-${dayOfMonth.append0()}")

        },ymd[0],ymd[1],ymd[2])
                .run {
                    //val datePicker = datePicker
                    if (maxDate > 0){
                        datePicker.maxDate = maxDate
                    }

                    show()
                }

    }



}